package com.tanhua.recommend.job;

import com.tanhua.domain.mongo.Movement;
import com.tanhua.domain.mongo.RecommendMovement;
import org.apache.commons.lang3.RandomUtils;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Set;

@Component
public class QuanziJob {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Scheduled(cron = "0/10 * * * * ?")
    public void synchronizedData(){
//        把redis中的数据放到mongo的recommend_movement表中

        Set<String> keys = redisTemplate.keys("QUANZI_PUBLISH_RECOMMEND_*");
        for (String key : keys) {


//            key: QUANZI_PUBLISH_RECOMMEND_62
//            获取用户id
            String userIdStr = key.replace("QUANZI_PUBLISH_RECOMMEND_","");
            long userId = Long.parseLong(userIdStr);

//            先删除之前的推荐数据
            mongoTemplate.remove(new Query(Criteria.where("userId").is(userId)),RecommendMovement.class);


            String values = redisTemplate.boundValueOps(key).get();  // "21,4,19,20,26,100099,28,10064,3,10020"
            String[] pids = values.split(",");

            for (String pid : pids) {

                Query query = new Query(Criteria.where("pid").is(Long.parseLong(pid)));
                Movement movement = mongoTemplate.findOne(query, Movement.class);
                if(movement==null){
                    continue;
                }
                RecommendMovement recommendMovement = new RecommendMovement();
                recommendMovement.setId(new ObjectId());
                recommendMovement.setCreated(new Date().getTime());

                recommendMovement.setUserId(userId);
                recommendMovement.setPid(Long.parseLong(pid));
                recommendMovement.setMovementId(movement.getId());
                recommendMovement.setScore(RandomUtils.nextDouble(30,60)); //冗余
                mongoTemplate.save(recommendMovement);
            }

            System.out.println("定时任务执行.........................");

        }

    }

    public  void testTest(){
        System.out.println("..........");
        System.out.println("hhhhhhhhhhhhh");
        System.out.println("VVVVVVVV");
    }

}
